package com.cong._203;

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode pointer, guard = new ListNode();
        pointer = guard;
        guard.next = head;
        while (pointer.next != null) {
            int nextVal = pointer.next.val;
            if (nextVal == val) {
                deleteNext(pointer);
            }else {
                pointer = pointer.next;
            }
        }
        return guard.next;
    }


    /**
     * 删除下个节点并返回下下个节点
     * @param node 节点
     */
    private void deleteNext(ListNode node) {
        assert node != null;
        ListNode next = node.next;
        node.next = next.next;
        next.next = null;
    }
}




class ListNode {
    int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
